<template>
    <div class="selectTreeClass" v-if="isMountedTree">
            <!-- clearable  @clear="clearableFn" -->

        <el-select
            v-model="mineStatusLabel"
            :disabled="depStatus"
            placeholder="请选择部门"
            
            multiple
            collapse-tags
            @remove-tag="remove"
            @visible-change="visibleChange"
            ref="selectRef"
            filterable
            size="small"
             
            :filter-method="filterMethod"
        >
            <div style="position: relative; height: 40px">
                <div style="position: absolute; left: 20px">
                    <el-button @click="confirm" size="small">确定</el-button>
                    <el-button @click="cancle" size="small">
                        取消子选项
                    </el-button>

                    <el-button @click="clearableFn(true)" size="small">
                        清空
                    </el-button>
                </div>
            </div>

            <el-option :value="mineStatusValue" style="height: auto">
                <el-tree
                    show-checkbox
                    node-key="deptCode"
                    :default-expand-all="true"
                    :default-checked-keys="defaultCheckedKeys"
                    :expand-on-click-node="false"
                    :data="treeData"
                    :check-strictly="true"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    ref="treeRef"
                    @check="handleCheckChange"
                    @check-change="checkChange"
                    @node-click="nodeClick"
                ></el-tree>
            </el-option>
        </el-select>
    </div>
</template>
  
  <script>
import { getTreeFramedepartmentList } from '@/api/system.js'
import { resolve } from '@antv/x6/lib/registry/router/manhattan/options'
export default {
    name: 'selectTreeCom',
    components: {},
    model: {
        prop: 'value',
        event: 'change',
    },
    props: {
        value: {
            type: String,
        },
        isAll: {
            type: Boolean,
            default: false,
        },
        depStatus: {
            type: Boolean,
            default: false,
        },
        errorMessage: {
            type: String,
            default: '请选定机构',
        },
    },
    data() {
        return {
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'deptName',
                id: 'deptCode',
            },
            isPoint:false,
            mineStatusLabel: [],
            mineStatusValue: [],
            isMountedTree: false,

            rowCancelObj: null,
            defaultCheckedKeys: null,
            isDeep: true,
            confirmStopWatch: false,
        }
    },
   async mounted() {
       await this.getTree()
       this.$emit("initFinished")
    },
    methods: {
        async getTree() {
            return new Promise(async (resolve,reject)=>{
                let { data, code } = await getTreeFramedepartmentList(
                    this.isAll
                )
                this.treeData = [this.$deepCopy(data)] //
                this.transName()
                if (code == 200) this.isMountedTree = true;
                resolve(true)
            })

        },
        transName(isFalse = true) {
            let arrIds = []
            try {
                if (this.value) {
                    arrIds = this.value.split(',')
                } else if (this.$store.state.user.baseInfo.deptCode) {
                    arrIds = [this.$store.state.user.baseInfo.deptCode]
                } else {
                    arrIds = [this.treeData[0].deptCode]
                }
            } catch (error) {}
            this.defaultCheckedKeys = arrIds // 树的
            this.idToObj(arrIds,isFalse)
             this.confirm(arrIds)
        },
        // tree节点过滤
        filterNode(value, data) {
            if (!value) return true
            return data.deptName.indexOf(value) !== -1
        },
        filterMethod(value) {
            this.$refs.treeRef.filter(value)
        },

        visibleChange(isShow) {
            if (isShow) {

            } else {
                // this.confirm()
            }
        },
        getRes(isDefaultArray){
                            let res
                if (Array.isArray(isDefaultArray)) {
                    res = isDefaultArray.join()
                } else {
                    res = this.$refs.treeRef.getCheckedKeys().join(',')
                    // if(!res){
                    //    res = this.value
                    // }
                }

                this.$emit('selected', res)
                this.$emit('change', res)
                return res;
        },
        confirm(isDefaultArray) {
            try {
                this.confirmStopWatch = true
                let res=  this.getRes(isDefaultArray)
                if (res && res.length) {
                    if(this.isPoint === false){
                        this.$refs.selectRef&& this.$refs.selectRef.blur()
                    }
                } else {
                    this.$message.error(this.errorMessage)
                }
                let that = this;
                setTimeout(() => {
                    that.confirmStopWatch = false
                })
            } catch (error) {
                console.log(error)
            }
        },
        cancle() {
            if (this.rowCancelObj) {
                let arr = this.diguiTree(this.rowCancelObj)

                arr.forEach((item) => {
                    this.$refs.treeRef.setChecked(item, false)
                    let indexVal = this.mineStatusValue.findIndex(
                        (obj) => obj.deptCode == item
                    )
                    if (indexVal != -1) {
                        this.mineStatusValue.splice(indexVal, 1)
                        this.mineStatusLabel.splice(indexVal, 1)
                    }
                })
            }
        },

        nodeClick(data1) {
            this.rowCancelObj = data1.children
        },
        handleCheckChange() {
            let res = this.$refs.treeRef.getCheckedNodes()
            let arrLabel = []
            let arr = []
            res.forEach((item) => {
                arrLabel.push(item.deptName)
                arr.push(item)
            })
            this.mineStatusValue = arr
            this.mineStatusLabel = arrLabel
        },
        checkChange(data1, selfStatus, data3) {
            if (this.isDeep === false) return
            // 1. 选中父 ,全选子.
            if (selfStatus === true) {
                let arr = this.digui(data1)

                arr.forEach((item) => {
                    setTimeout(() => {
                        this.$refs.treeRef.setChecked(item, true, true)
                    })
                })
            } else {
                this.rowCancelObj = [data1, ...data1.children]
                this.cancle()
                // let arr = this.digui(data1)
                //     arr.forEach(item=>{

                //         setTimeout(()=>{
                //             this.$refs.treeRef.setChecked(item,false)
                //         })
                //         // if(indexVal != -1){
                //         //     this.mineStatusValue.splice(indexVal,1)
                //         //     this.mineStatusLabel.splice(indexVal,1)
                //         // }
                //     })
            }
        },
        idToObj(ids, isDeep = true) {
            this.mineStatusValue = []
            this.mineStatusLabel = []
            ids.forEach((id) => {
                let obj = this.treeSearchObj(id)
                this.isDeep = isDeep
                setTimeout(() => {
                    this.isDeep = true
                }, 300) // 外层渲染层是 定时器0ms,这里延迟恢复.
                this.mineStatusValue.push(obj)
                this.mineStatusLabel.push(obj.deptName)
            })
        },
        treeSearchObj(id) {
            function findNodeById(tree, id) {
                if (!tree || !Array.isArray(tree)) {
                    return null
                }

                for (const node of tree) {
                    if (node.deptCode === id) {
                        return node // 返回匹配的节点
                    }
                    // 这里看看怎么回事,还是有子级.  然后就可以继续写其他需求了
                    if (node.children && node.children.length) {
                        const foundNode = findNodeById(node.children, id) // 递归搜索子节点
                        if (foundNode) {
                            return foundNode // 若找到匹配的节点，则返回节点
                        }
                    }
                }

                return {} // 若未找到匹配的节点，返回 null
            }
            return findNodeById(this.treeData, id)
        },
        digui(obj) {
            let newArr = []

            function di(obj) {
                newArr.push(obj.deptCode)
                obj.children &&
                    obj.children.length > 0 &&
                    obj.children.forEach((item) => di(item))
            }

            newArr.push(obj.deptCode)
            obj.children &&
                obj.children.length > 0 &&
                obj.children.forEach((item) => di(item))
            return newArr
        },
        diguiTree(arr) {
            let newArr = []
            function di(obj) {
                newArr.push(obj.deptCode)
                obj.children &&
                    obj.children.length > 0 &&
                    obj.children.forEach((item) => di(item))
            }
            arr.forEach((item) => di(item))
            return newArr
        },
        //当多选时候，删除小标签时，将删除的子节点状态改为未勾选
        remove(val) {
            let selectNodes = this.$refs.treeRef.getCheckedNodes()
            for (
                let i = 0;
                i < this.$refs.treeRef.getCheckedNodes().length;
                i++
            ) {
                if (selectNodes[i].deptName == val) {
                    let arrIds = this.digui(selectNodes[i])
                    arrIds &&
                        arrIds.forEach((item, ind) => {
                            this.$refs.treeRef.setChecked(
                                arrIds[ind],
                                false,
                                true
                            )
                            let indexVal = this.mineStatusValue.findIndex(
                                (obj) => obj.deptCode == item
                            )
                            if (indexVal != -1) {
                                this.mineStatusValue.splice(indexVal, 1)
                                this.mineStatusLabel.splice(indexVal, 1)
                            }
                        })
                }
            }
        },
        //清除所有选项
        clearableFn(isPoint) {
            // 这里的清空时间处理下
            this.$refs.treeRef.setCheckedKeys([])
            this.mineStatusValue = []
            this.mineStatusLabel = []
            this.defaultCheckedKeys = []
            // this.defaultCheckedKeys = [this.value]
            this.isPoint = isPoint;
            setTimeout(()=>{
                this.transName(false)
                setTimeout(()=>{
                    this.isPoint = false;
                })
            },100)
            // this.confirm()
            // this.getTree()
        },
    },
    // watch: {
    //     value(newV) {
    //         if (newV && !this.confirmStopWatch) {
    //             this.getTree()
    //         }
    //     },
    // },
}
</script>
  
<style lang = "scss" scoped>
:deep .el-select {
    width: 100%;
}
:deep .el-input {
    min-width: 285px;
    width: 100%;
}
::v-deep .el-tag.el-tag--info .el-tag__close {
    display: none;
}
</style>

<style lang="scss">
.el-select-dropdown.is-multiple .el-select-dropdown__item {
    padding-right: 20 !important;
}
.el-select-dropdown__item.hover {
    background-color: transparent;
}
</style>
  